package com.wangcw.minicat;

import com.minicat.sdk.MiniCatServlet;
import com.minicat.sdk.Request;
import com.minicat.sdk.Response;
import server.HttpServlet;

import java.io.File;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestListenter extends Thread {

    public static Map<String,MiniCatServlet> miniCatServletMap = new HashMap<>();


    private Socket socket;

    public RequestListenter(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String path = "webapp/demo/WEB-INF/classes/com/example/demo/servlet/HelloServlet.class";
            File file = new File(path);
            DynamicClassLoader dynamicClassLoader = new DynamicClassLoader();
            Class<MiniCatServlet> aClass = (Class<MiniCatServlet>) dynamicClassLoader.findClass(path);
            aClass.getMethod("process", com.minicat.sdk.Request.class, com.minicat.sdk.Response.class)
                    .invoke(aClass.getDeclaredConstructor().newInstance(),request,response);
            MiniCatServlet miniCatServlet = miniCatServletMap.get(path);
            miniCatServlet.process(request,response);

            //
            // 静态资源处理
//            if(servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }
            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
